package com.fashiontextile.user.controller;

import com.fashiontextile.common.annotation.RequireRole;
import com.fashiontextile.common.constant.AppConstants;
import com.fashiontextile.common.constant.TokenConstants;
import com.fashiontextile.common.entity.R;
import com.fashiontextile.common.utils.AliyunOSSUtils;
import com.fashiontextile.user.entity.User;
import com.fashiontextile.user.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * @author brooke_zb
 */
@RestController
@AllArgsConstructor
public class UserController {
    UserService userService;
    AliyunOSSUtils ossUtils;
    private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    @GetMapping("/uid/{uid:\\d+}")
    public R<User> getUserByUid(@PathVariable Long uid) {
        User user = userService.selectByUid(uid);
        if (user == null) {
            return R.fail("找不到该用户");
        } else {
            return R.success(user);
        }
    }

    @GetMapping("/username/{username}")
    public R<User> getUserByUsername(@PathVariable String username) {
        User user = userService.selectByUsername(username);
        if (user == null) {
            return R.fail("找不到该用户");
        } else {
            return R.success(user);
        }
    }

    @GetMapping("/email/{email}")
    public R<User> getUserByEmail(@PathVariable String email) {
        User user = userService.selectByEmail(email);
        if (user == null) {
            return R.fail("找不到该用户");
        } else {
            return R.success(user);
        }
    }

    @PostMapping("/user")
    @RequireRole(AppConstants.ROLE_ADMIN)
    public R<?> register(@RequestBody User user) {
        Integer result = userService.insertUser(user);
        if (result > 0) {
            return R.success("注册成功！");
        } else {
            return R.fail("注册失败！");
        }
    }

    @GetMapping("/me")
    public R<User> getMyInfo(@RequestHeader(TokenConstants.LOGIN_UID_HEADER) Long uid) {
        User userInfo = userService.selectByUid(uid);
        if (userInfo == null) {
            return R.fail("查询失败");
        } else {
            userInfo.setPassword(null);
            return R.success(userInfo);
        }
    }

    @PatchMapping("/me/email")
    public R<String> ModifyEmail(@RequestBody Map<String, String> map, @RequestHeader(TokenConstants.LOGIN_UID_HEADER) Long uid) {
        // 从map获取邮箱信息
        String email = map.get("email");

        if (email == null) {
            return R.fail("缺少必要字段");
        }
        Integer result = userService.updateEmail(email, uid);
        if (result > 0) {
            return R.success("成功修改");
        } else {
            return R.success("修改失败");
        }
    }

    @PatchMapping("/me/avatar")
    public R<?> modifyAvatar(MultipartFile avatar, @RequestHeader(TokenConstants.LOGIN_UID_HEADER) Long uid) {
        String fileExtension = Objects.requireNonNull(avatar.getOriginalFilename()).substring(avatar.getOriginalFilename().lastIndexOf("."));
        try {
            R<?> avatarUrl = ossUtils.uploadMultipart(avatar, UUID.randomUUID() + fileExtension);
            String avatarURlData = (String) avatarUrl.getData();
            userService.updateAvatar(avatarURlData, uid);
            return avatarUrl;
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("上传失败");
        }
    }

    @PatchMapping("/me/password")
    public R<?> modifyPassword(@RequestBody Map<String, String> map, @RequestHeader(TokenConstants.LOGIN_UID_HEADER) Long uid) {
        User user = userService.selectByUid(uid);
        String oldPassword = map.get("oldPassword");
        String newPassword = map.get("newPassword").trim();
        if (newPassword.length() < 8) {
            return R.fail("密码不能少于8位");
        }
        if (!encoder.matches(oldPassword, user.getPassword())) {
            return R.fail("当前密码错误");
        }
        return userService.updatePasswold(encoder.encode(newPassword), uid) > 0 ? R.success("成功修改") : R.fail("修改失败");
    }

    @GetMapping("")
    @RequireRole(AppConstants.ROLE_ADMIN)
    public R<?> getAllUser(@RequestParam(required = false, defaultValue = "1") Integer page, @RequestParam(required = false) String keyword) {
        PageHelper.startPage(page, 10);
        List<User> userList = userService.getAllUser(keyword);
        if (userList == null) {
            return R.fail("查询用户列表失败");
        }
        PageInfo<User> UserPageInfo = new PageInfo<>(userList);
        if (userList.size() > 0) {
            return R.success(UserPageInfo);
        }
        return R.fail("查询用户列表失败");
    }

    @PatchMapping("/{uid}/status/{status:^[01]$}")
    @RequireRole(AppConstants.ROLE_ADMIN)
    public R<?> updateUserStatus(@PathVariable("uid") Long uid, @PathVariable("status") Integer status) {
        if (status == 0) {
            return userService.updateUserStatus(uid, status) > 0 ? R.success("封禁用户成功") : R.fail("封禁用户失败");
        } else {
            return userService.updateUserStatus(uid, status) > 0 ? R.success("解封用户成功") : R.fail("解封用户失败");
        }
    }

    @PutMapping("/user/uid/{uid:\\d+}/rid/{rid:\\d+}")
    R<?> changeRoleByUid(@PathVariable("uid") long uid, @PathVariable("rid") Integer rid){
        return userService.changeRoleByUid(uid,rid);
    }
}
